<template>
  <div class="tts-video-container">
    <div class="tts-header">
      <TtsVideoHeader v-model="videoData" :onSubmit="action.submitVideos" />
    </div>
    <div class="tts-content">
      <div class="tts-sidebar">
        <TtsItemList v-model="videoData" />
      </div>
      <div class="tts-main">
        <div class="tts-assignment-area">
          <TtsAssignment
            v-model="videoData"
            :modelSource="state.modelSource"
            @assignAvatar="action.assignAvatar"
            @queryModels="action.queryModels"
            @switchSource="action.switchModelSource"
            :listener="listener"
          />
        </div>
      </div>
    </div>
    <BatchListener ref="listener" />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { useRoute, useRouter } from 'vue-router'
import TtsVideoHeader from '../header/TtsVideoHeader.vue';
import TtsItemList from '../items/TtsItemList.vue';
import TtsAssignment from '../assign/TtsAssignment.vue';
import BatchListener from '../../batch/listener/BatchListener.vue';
import { modelPage, saveVideo, makeVideo, getCommonModelList, makeVideoCommon, findModelCommon } from '@renderer/api'
import { getAssetPathByKey } from '@renderer/api/assetPaths'

const assetPaths = ref('')

const router = useRouter();
const route = useRoute();

const listener = ref(null);

// 添加状态对象，包含模型源
const state = reactive({
  modelSource: 'common', // 默认使用公共库模型
  loading: false
});

// 视频数据模型
const videoData = defineModel({
  default: () => ({
    name: '批量小语种任务',
    contentItems: [], // 音频内容项数组
    models: [], // 数字人模型数组
    assignments: [], // 内容项与数字人的关联数组
  }),
});

const action = {
  // 添加切换模型源的方法
  async switchModelSource(source) {
    // 如果源没有变化，不需要处理
    if (state.modelSource === source) return;

    state.loading = true;
    try {
      // 更新模型源
      state.modelSource = source;

      // 清空所有分配关系
      if (videoData.value.assignments) {
        videoData.value.assignments = videoData.value.assignments.map(assignment => ({
          ...assignment,
          modelId: null
        }));
      }

      // 清空模型列表
      videoData.value.models = [];

      // 根据不同的源加载对应的模型
      if (source === 'common') {
        await action.queryCommonModels();
        MessagePlugin.success('已切换到公共库模型');
      } else {
        await action.queryModels();
        MessagePlugin.success('已切换到本地模型');
      }

      // 更新URL参数，但不刷新页面
      const newQuery = { ...route.query, common: source === 'common' };
      router.replace({ query: newQuery });

    } catch (error) {
      console.error('切换模型源失败', error);
      MessagePlugin.error('切换模型源失败: ' + error.message);
    } finally {
      state.loading = false;
    }
  },
  // 查询公共库的数字人模型
  async queryCommonModels(searchTerm = '') {
    state.loading = true;
    try {
      const params = {
        page: 1,
        pageSize: 12,
        name: searchTerm
      };

      const result = await getCommonModelList(params);
      if (result && result.data && result.data.records) {
        // 将API返回的数据格式转换为应用所需的格式
        const formattedModels = result.data.records.map(model => ({
          id: model.id,
          name: model.name,
          video_path: `${assetPaths.value}/${model.videoPath}`,
          audio_Path: `${assetPaths.value}/${model.audioPath.replace("\\","/")}`,
          image_path: `${assetPaths.value}/${model.imagePath}`,
          voice_id: model.voiceId,
          isCommonModel: true, // 添加一个标志，标识这是公共库模型
          primaryCategoryId: model.primaryCategoryId,
          secondaryCategoryId: model.secondaryCategoryId,
          tertiaryCategoryId: model.tertiaryCategoryId,
          primaryCategoryName: model.primaryCategoryName,
          secondaryCategoryName: model.secondaryCategoryName,
          tertiaryCategoryName: model.tertiaryCategoryName,
        }));

        // 更新模型列表
        videoData.value = {
          ...videoData.value,
          models: formattedModels
        };
      } else {
        MessagePlugin.warning('未找到公共库数字人模型');
        videoData.value = {
          ...videoData.value,
          models: []
        };
      }
    } catch (error) {
      console.error('查询公共库模型列表失败', error);
      MessagePlugin.error('查询公共库模型列表失败: ' + error.message);
      videoData.value = {
        ...videoData.value,
        models: []
      };
    } finally {
      state.loading = false;
    }
  },
  // 查询本地的数字人模型
  async queryModels(searchTerm = '') {
    state.loading = true;
    try {
      const result = await modelPage({
        name: searchTerm,
        page: 1,
        pageSize: 12
      });
      if (result && result.list) {
        // 创建一个新对象以确保Vue能检测到变化
        videoData.value = {
          ...videoData.value,
          models: result.list
        };
      } else {
        MessagePlugin.warning('未找到数字人模型');
        videoData.value = {
          ...videoData.value,
          models: []
        };
      }
    } catch (error) {
      console.error('查询模型列表失败', error);
      MessagePlugin.error('查询模型列表失败: ' + error.message);
      videoData.value = {
        ...videoData.value,
        models: []
      };
    }
  },

  // 分配数字人模型到内容项
  assignAvatar(contentId, modelId) {
    // 确保 assignments 已经初始化
    if (!videoData.value.assignments) {
      videoData.value.assignments = [];
    }

    const assignmentIndex = videoData.value.assignments.findIndex(
      assignment => assignment.contentId === contentId
    );

    const newAssignments = [...videoData.value.assignments];

    if (assignmentIndex !== -1) {
      // 更新现有分配关系
      newAssignments[assignmentIndex] = {
        ...newAssignments[assignmentIndex],
        modelId
      };
    } else {
      // 创建新的分配关系
      newAssignments.push({
        contentId,
        modelId,
      });
    }

    // 更新 assignments
    videoData.value = {
      ...videoData.value,
      assignments: newAssignments
    };
  },

  // 提交批量任务
  async submitVideos() {
    try {
      // 检查是否有内容项
      if (!videoData.value.contentItems || videoData.value.contentItems.length === 0) {
        MessagePlugin.warning('没有可用的音频内容');
        return;
      }

      // 检查是否所有内容项都已分配模型
      const unassignedItems = videoData.value.assignments.filter(a => !a.modelId);
      if (unassignedItems.length > 0) {
        MessagePlugin.warning('有内容项尚未分配数字人，请完成分配');
        return;
      }

      // 准备要创建的视频任务
      const successIds = [];
      const videoTaskA = [];

      // 创建成功的计数
      let successCount = 0;
      let failCount = 0;

      // 显示进度提示
      await MessagePlugin.loading('正在提交批量任务...');

      // 遍历所有分配关系
      for (const assignment of videoData.value.assignments) {
        if (!assignment.modelId) continue;

        const contentItem = videoData.value.contentItems.find(item => item.id === assignment.contentId);
        const model = await findModelCommon(assignment.modelId)

        if (!contentItem || !model) continue;

        try {
          const videoTask = {
            model_id: assignment.modelId,
            name: `${model.name}_${contentItem.name || '无标题'}`,
            audio_path: contentItem.audioUrl,
            is_common_model: state.modelSource === 'common',
            caption_path: `${contentItem.caption_path}`
          };

          videoTaskA.push(videoTask);

          // 使用saveVideo API创建视频记录
          const videoId = await saveVideo(videoTask);

          if (videoId) {
            successIds.push(videoId);
            successCount++;
          }
        } catch (error) {
          console.error('创建视频任务失败:', error);
          failCount++;
          continue; // 继续处理其它任务
        }
      }

      console.log(JSON.stringify(videoTaskA))

      // 如果有成功创建的视频任务，开始生成视频
      if (successIds.length > 0) {
        MessagePlugin.success(`成功创建${successCount}个视频任务，开始生成视频`);

        // 逐个触发视频生成
        for (const videoId of successIds) {
          try {
            if (state.modelSource === 'common'){
              await makeVideoCommon(videoId);
            }else {
              await makeVideo(videoId);
            }
          } catch (error) {
            console.error(`视频生成失败 (ID: ${videoId}):`, error);
          }
        }

        MessagePlugin.success(`任务已提交，共${successCount}个视频${failCount > 0 ? `，${failCount}个失败` : ''}`);

        // 跳转到首页或其他页面
        setTimeout(() => {
          router.push('/home');
        }, 2000);
      } else {
        MessagePlugin.error('没有成功创建任何视频任务');
      }
    } catch (error) {
      console.error('提交视频任务失败', error);
      MessagePlugin.error('提交视频任务失败：' + (error.message || '未知错误'));
    }
  }
};

onMounted(async () => {
  // 从本地存储加载音频项目
  const savedAudioItems = localStorage.getItem('ttsAudioItems');
  if (savedAudioItems) {
    try {
      const audioItems = JSON.parse(savedAudioItems);
      videoData.value.contentItems = audioItems;

      // 为每个音频项创建分配关系
      audioItems.forEach(item => {
        videoData.value.assignments.push({
          contentId: item.id,
          modelId: null
        });
      });

      // 清除本地存储
      localStorage.removeItem('ttsAudioItems');
    } catch (error) {
      console.error('解析音频数据失败:', error);
    }
  }

  await getAssetPathByKey('model').then(result => {
    assetPaths.value = result.path_value;
  })

  // 检查是否有common参数，决定加载公共库还是本地模型
  const useLocalModels = route.query.common === 'false' || route.query.common === false;

  // 设置初始模型源
  state.modelSource = useLocalModels ? 'local' : 'common';

  if (state.modelSource === 'local') {
    // 加载本地模型
    await action.queryModels();
  } else {
    // 默认加载公共库模型
    await action.queryCommonModels();
  }
});
</script>

<style lang="less" scoped>
.tts-video-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #ffffff;  // 深色背景改为白色
  color: #333333;  // 白色文字改为深灰色

  .tts-header {
    height: 60px;
    border-bottom: 1px solid #e0e0e0;  // 添加边框分隔线，增强层次感
  }

  .tts-content {
    display: flex;
    flex: 1;
    overflow: hidden;

    .tts-sidebar {
      width: 300px;
      border-right: 1px solid #e0e0e0;  // 黑色边框改为浅灰色
      background-color: #f9f9f9;  // 深色背景改为浅灰白色，与主区域区分
      overflow: hidden;
      box-shadow: 1px 0 3px rgba(0, 0, 0, 0.03);  // 添加轻微阴影增强立体感
    }

    .tts-main {
      flex: 1;
      display: flex;
      flex-direction: column;
      overflow: hidden;
      background-color: #ffffff;  // 确保主区域为白色背景

      .tts-assignment-area {
        flex: 1;
        overflow: auto;
        padding: 20px;
        background-color: #fafafa;  // 分配区域使用浅灰背景，增强区分度
      }
    }
  }
}
</style>
